package java.socket_3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Server_3 {
   private ServerSocket serverSocket;
   //创建一个用于储存客户端输出流的列表
   private List<PrintWriter> allOut =new ArrayList<PrintWriter>();
 public Server_3(){
     try {
         System.out.println("正在启动服务器");
         //开放一个端口用于链接客户端
         serverSocket=new ServerSocket(8088);
         System.out.println("服务端启动完毕");
     } catch (IOException e) {
         throw new RuntimeException(e);
     }
 }
    public void start(){
        try {
            System.out.println("正在等待客户端链接。。。。");
            //链接客户端
            Socket socket = serverSocket.accept();
            System.out.println("一个客户端链接了");
            //为线程准备导入内容
            ClientHandler handler=new ClientHandler(socket);
            //创建线程
            Thread thread = new Thread(handler);
            //启动线程
            thread.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }


    public static void main(String[] args) {

    }
    private class ClientHandler implements Runnable {
     //接入外部数据
        private Socket socket;
        //创建一个字符串用于接受ip
        private String host;
      public   ClientHandler(Socket socket) {
            this.socket = socket;
            //获取计算机ip,通过socket
            host = socket.getInetAddress().getHostAddress();

        }

        @Override
        public void run() {

            BufferedReader br = null;
            PrintWriter pw = null;
            try {

                //创建低级输入流接入socket
                InputStream is = socket.getInputStream();
                //创建读写接入流，编码格式UTF-8
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                //缓冲输入流
                br = new BufferedReader(isr);
                //创建低级输出流
                OutputStream os= socket.getOutputStream();
                //创建文本输出流，规定UTF-8
                OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
                //创建缓冲输出流
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);
                synchronized (allOut){//同步监视器对象获取资源
                    allOut.add(pw);//将输出流加入集合,视为增加在线人数
                    sendMessage(host+"上线了：当前在线人数："+allOut.size());   //输出上线人及当前人数
                    String line;
                    while ((line = br.readLine()) != null) {
                        sendMessage(host +"说"+line);

                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                //处理客户端下线操作
                synchronized (allOut) {
                    //下线后移除集合
                    allOut.remove(pw);
                }
                sendMessage(host + "下线了，当前人数为"+allOut.size());

                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
      }
        private void sendMessage(String message){
            System.out.println(message);
            //设置并发规则
            synchronized (allOut){
                for (PrintWriter pw: allOut) {
                    //循环集合里的每个输出流
                    pw.println(message);
                }
            }

        }
    }

}
